#include <REGX52.H>

sbit OneWire_DQ=P3^7;

void Delay490us()		//@11.0592MHz
{
	unsigned char i;

	i = 223;
	while (--i);
}

void Delay70us()		//@11.0592MHz
{
	unsigned char i; 
	i = 29;
	while (--i);
}

void Delay10us()		//@11.0592MHz
{
	unsigned char i;

	i = 2;
	while (--i);
}

void Delay50us()		//@11.0592MHz
{
	unsigned char i;
	i = 20;
	while (--i);
}


void Delay5us()		//@11.0592MHz
{
}


//延时要求很高 us级别， 如果用到定时器，这里的每个函数都要先把定时器失效 EA=0，延时完成再EA=1
unsigned char OneWire_Init() {
	unsigned char AckBit;
	OneWire_DQ=1;
	OneWire_DQ=0;
	Delay490us();
	
	OneWire_DQ=1;
	
	Delay70us();
	AckBit=OneWire_DQ; //读当前电平值
	Delay490us();      //补充延时
	return AckBit;
}


void OneWire_SendBit(unsigned char Data) {
	OneWire_DQ=0;
	Delay10us();
	OneWire_DQ=Data;
	Delay50us();
	OneWire_DQ=1;
}

unsigned char OneWire_ReceiveBit(){ 
	unsigned char Bit;
	OneWire_DQ=0;
	Delay5us();
	OneWire_DQ=1;
	Delay5us();
	Bit = OneWire_DQ;
	Delay50us();
	return Bit; 
}

void OneWire_SendByte(unsigned char Data) {
	unsigned char i;
	for(i=0;i<8;i++) {
		OneWire_SendBit(Data&(0x01<<i));
	}
}


unsigned char OneWire_ReceiveByte() {
	unsigned char i;
	unsigned char Data = 0;
	for(i=0;i<8;i++) {
			if(OneWire_ReceiveBit()){
				Data|=(0x01<<i);
			}
	}
	return Data;
}